package com.seelyn.rhea.mvc.internal;

import com.seelyn.rhea.mvc.context.Request;
import com.seelyn.rhea.mvc.context.Response;
import com.seelyn.rhea.mvc.internal.matcher.RheaMatcher;
import com.seelyn.rhea.mvc.internal.matcher.UriMatcher;
import com.seelyn.rhea.mvc.route.Resolver;
import com.seelyn.rhea.mvc.route.ResolverMatching;

import java.util.Map;

/**
 * @author slacrey
 * @since 2016/1/24
 */
public abstract class InternalResolver implements ResolverMatching {

    private final UriMatcher<String> matcher;

    protected InternalResolver(String path) {
        matcher = RheaMatcher.path(path);
    }

    public abstract String getPath();

    @Override
    public boolean matching(String path) {
        return matcher.matching(path);
    }

    @Override
    public Map<String, String> getPathParams(String path) {
        return matcher.getPathParams(path);
    }

    static InternalResolver create(final String path, final Resolver resolver) {
        return new RheaInternalResolver(path, resolver);
    }

    private static final class RheaInternalResolver extends InternalResolver {

        private final String path;
        private final Resolver resolver;

        private RheaInternalResolver(String path, Resolver resolver) {
            super(path);
            this.path = path;
            this.resolver = resolver;
        }

        @Override
        public String getPath() {
            return path;
        }

        @Override
        public void handle(Request request, Response response, Exception ex) {

            resolver.handle(request, response, ex);
        }
    }
}
